<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 搜索 -->
            <el-row :gutter="20">
                <el-col :span="14">
                    <el-input placeholder="请输入内容" v-model='queryInfo.query' clearable @clear='getGoodsList'>
                        <el-button slot="append" icon="el-icon-search" @click='getGoodsList'></el-button>
                    </el-input>
                </el-col>
                <el-col :span="8">
                    <el-button type="primary" @click='goAddpage'>添加商品</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="goodslist" style="width: 100%" border stripe>
                <el-table-column type='index' label="/"></el-table-column>
                <el-table-column prop="goods_name" label="商品名称"></el-table-column>
                <el-table-column prop="goods_price" label="商品价格（元）" width='110px'></el-table-column>
                <el-table-column prop="goods_weight" label="商品重量(kg)" width='120px'></el-table-column>
                <el-table-column prop="add_time" label="创建时间" width='200px'>
                    <template slot-scope="scope">
                        {{scope.row.add_time | dateFormat}}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size='mini'
                            @click='showEditDialog(scope.row.goods_id)'>
                        </el-button>
                        <!-- 删除按钮 -->
                        <template>
                            <el-button type="danger" icon="el-icon-delete" size='mini'
                                @click='removeGoodsById(scope.row.goods_id)'></el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[10, 15, 18, 23]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" background>
            </el-pagination>
        </el-card>

        <!-- 编辑操作 -->
        <el-dialog title="编辑商品" :visible.sync="Visible" width="70%" @close="addDialogClose">
            <!-- 内容主体区域 -->
            <el-form :model="listVisible" :rules="listformrules" ref="listfformref">
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="listVisible.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格（元）" prop="goods_price">
                    <el-input v-model="listVisible.goods_price"></el-input>
                </el-form-item>
                <el-form-item label="商品重量(kg)" prop="goods_weight">
                    <el-input v-model="listVisible.goods_weight"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="Visible = false">取 消</el-button>
                <el-button type="primary" @click="listadduser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: 'list',
        data() {
            return {
                // 获取商品列表数据对象
                queryInfo: {
                    // 搜索关键字
                    query: '',
                    // 当前的页数
                    pagenum: 1,
                    // 当前每页显示多少条数据
                    pagesize: 10
                },
                // 所有的总数据条数
                total: 0,

                // 所有的商品列表 信息
                goodslist: [],
                // 显示与隐藏
                Visible: false,
                // 商品的数据 对象
                listVisible: {},
                // 添加表单验证规则对象
                listformrules: {
                    goods_name: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                    ],
                    goods_price: [
                        { required: true, message: '请输入商品价格（元）', trigger: 'blur' },
                    ],
                    goods_weight: [
                        { required: true, message: '请输入商品重量(kg)', trigger: 'blur' },
                    ]
                },
            }
        },
        created() {
            this.getGoodsList()
        },
        methods: {
            // 监听 pagesize 改变的事件
            handleSizeChange(newSize) {
                // console.log(newSize);
                this.queryInfo.pagesize = newSize
                // newSize 数据变化 重新发起数据请求 获取页面数据
                this.getGoodsList()
            },
            // 监听 页码值 改变的事件
            handleCurrentChange(newPage) {
                // console.log(newPage);
                this.queryInfo.pagenum = newPage
                // newPage 数据变化 重新发起数据请求 获取页面数据
                this.getGoodsList()
            },
            // 查询 所有的商品列表数据
            async getGoodsList() {
                const { data: res } = await this.$http.get(`goods`, { params: this.queryInfo })
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error("获取商品列表失败！")
                }
                //赋值
                this.goodslist = res.data.goods
                this.total = res.data.total
            },
            async showEditDialog(id) {
                // console.log(id);
                this.Visible = true
                const { data: res } = await this.$http.get(`goods/${id}`)
                // console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取商品数据失败！')
                }
                this.listVisible = res.data
            },
            // 监听添加角色对话框的关闭事件-表单的重置
            addDialogClose() {
                this.$refs.listfformref.resetFields()
            },
            // 根据点击 删除按钮
            removeGoodsById(id) {
                this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async (suc) => {
                    const { data: res } = await this.$http.delete(`goods/${id}`)
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除商品数据失败！')
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    // console.log(suc);
                    this.getGoodsList()
                }).catch((err) => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                    // console.log(err);
                });
            },
            //添加商品 跳转
            goAddpage() {
                this.$router.push('goods/add')
            },
            // 点击确定按钮
            listadduser() {
                //接收校验的结果 valid
                this.$refs.listfformref.validate(async valid => {
                    // console.log(valid);
                    if (!valid) {// 校验不通过
                        // console.log(!valid,11);
                        return this.$message.error('更新失败！')
                    }
                    // console.log(this.listVisible, 11);
                    // 可以发起网络请求
                    const { data: res } = await this.$http.put(`goods/${this.listVisible.goods_id}`, {
                        goods_name:this.listVisible.goods_name,
                        goods_price:this.listVisible.goods_price,
                        goods_number:this.listVisible.goods_number,
                        goods_weight:this.listVisible.goods_weight,
                        goods_cat:this.listVisible.goods_cat,
                    })
                    // console.log(res);
                    if (res.meta.status !== 200) {
                        this.$message.error('更新数据失败了！')
                    } else {
                        this.$message.success('更新数据成功！')
                        // 隐藏添加用户的对话框
                        this.Visible = false
                        // 重新获取用户列表数据
                        this.getGoodsList()
                    }
                })
            }
        },
    }
</script>

<style scoped>
    .el-row {
        margin: 15px 0;
    }

    .el-table {
        margin-bottom: 15px;
    }
</style>